//
//  JSDemoHomeVC.m
//  JSBaseProject
//
//  Created by Apple on 2017/11/7.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "JSDemoHomeVC.h"
#import "JSBookReaderController.h"
#import "TestFriendCycleVC.h"
@interface JSDemoHomeVC ()

@property(nonatomic, strong) QMUIOrderedDictionary *dataSource;
@property(nonatomic, strong) QMUIGridView *gridView;
@property(nonatomic, strong) UIScrollView *scrollView;

@end

@implementation JSDemoHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.    
    self.dataSource = [[QMUIOrderedDictionary alloc] initWithKeysAndObjects:
                       @"阅读器", UIImageMake(@"icon_tabbar_1_selected"),
                       @"朋友圈", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUITextView", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUITextField", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUISlider", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUIAlertController", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUITableView", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUICollectionViewLayout", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUISearchController", UIImageMake(@"icon_tabbar_1_selected"),
                       @"ViewController Orientation", UIImageMake(@"icon_tabbar_1_selected"),
                       @"QMUINavigationController", UIImageMake(@"icon_tabbar_1_selected"),
                       @"UITabBarItem+QMUI", UIImageMake(@"icon_tabbar_1_selected"),
                       @"UIColor+QMUI", UIImageMake(@"icon_tabbar_1_selected"),
                       @"UIImage+QMUI", UIImageMake(@"icon_tabbar_1_selected"),
                       @"UIFont+QMUI", UIImageMake(@"icon_tabbar_1_selected"),
                       @"UIView+QMUI", UIImageMake(@"icon_tabbar_1_selected"),
                       @"NSObject+QMUI", UIImageMake(@"icon_tabbar_1_selected"),
                       nil];
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:self.scrollView];
    _gridView = [[QMUIGridView alloc] init];
    for (NSInteger i = 0, l = self.dataSource.count; i < l; i++) {
        [self.gridView addSubview:[self generateButtonAtIndex:i]];
    }
    [self.scrollView addSubview:self.gridView];
    
}
- (UIView *)generateButtonAtIndex:(NSInteger )index {
    NSString *keyName = self.dataSource.allKeys[index];
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:keyName attributes:@{NSForegroundColorAttributeName: UIColorGray6, NSFontAttributeName: UIFontMake(11), NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:12 lineBreakMode:NSLineBreakByTruncatingTail textAlignment:NSTextAlignmentCenter]}];
    UIImage *image = (UIImage *)[self.dataSource objectForKey:keyName];
    
    QMUIButton *button = [[QMUIButton alloc] init];
    button.imagePosition = QMUIButtonImagePositionTop;
    UIColor *tintColor = [QDThemeManager sharedInstance].currentTheme.themeGridItemTintColor;
    if (tintColor) {
        button.tintColor = tintColor;
        button.adjustsImageTintColorAutomatically = YES;
    } else {
        button.tintColor = nil;
        button.adjustsImageTintColorAutomatically = NO;
    }
    [button setAttributedTitle:attributedString forState:UIControlStateNormal];
    [button setImage:image forState:UIControlStateNormal];
    button.tag = index;
    [button addTarget:self action:@selector(handleGirdButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}
- (void)setNavigationItemsIsInEditMode:(BOOL)isInEditMode animated:(BOOL)animated{
    [super setNavigationItemsIsInEditMode:isInEditMode animated:animated];
    self.title = @"首页";
}
-(void)handleGirdButtonEvent:(UIButton *)sender {
    
    NSString *keyName = self.dataSource.allKeys[sender.tag];
    [self didSelectCellWithTitle:keyName];
}
-(void)didSelectCellWithTitle:(NSString *)title{
    QMUILog(@"%@", title);
    UIViewController *vc = nil;
    if ([title isEqualToString:@"阅读器"]) {
        vc = [[JSBookReaderController alloc] init];
    }else if ([title isEqualToString:@"朋友圈"]){
        vc = [[TestFriendCycleVC alloc] init];
    }
    if (vc) {
        [self.navigationController pushViewController:vc animated:YES];
    }

}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.scrollView.frame = self.view.bounds;
    
    CGFloat gridViewWidth = CGRectGetWidth(self.scrollView.bounds) - UIEdgeInsetsGetHorizontalValue(self.scrollView.qmui_safeAreaInsets);
    
    if (CGRectGetWidth(self.view.bounds) <= [QMUIHelper screenSizeFor55Inch].width) {
        self.gridView.columnCount = 3;
        CGFloat itemWidth = flat(gridViewWidth / self.gridView.columnCount);
        self.gridView.rowHeight = itemWidth;
    } else {
        CGFloat minimumItemWidth = flat([QMUIHelper screenSizeFor55Inch].width / 3.0);
        CGFloat maximumItemWidth = flat(gridViewWidth / 5.0);
        CGFloat freeSpacingWhenDisplayingMinimumCount = gridViewWidth / maximumItemWidth - floor(gridViewWidth / maximumItemWidth);
        CGFloat freeSpacingWhenDisplayingMaximumCount = gridViewWidth / minimumItemWidth - floor(gridViewWidth / minimumItemWidth);
        if (freeSpacingWhenDisplayingMinimumCount < freeSpacingWhenDisplayingMaximumCount) {
            // 按每行最少item的情况来布局的话，空间利用率会更高，所以按最少item来
            self.gridView.columnCount = floor(gridViewWidth / maximumItemWidth);
            CGFloat itemWidth = floor(gridViewWidth / self.gridView.columnCount);
            self.gridView.rowHeight = itemWidth;
        } else {
            self.gridView.columnCount = floor(gridViewWidth / minimumItemWidth);
            CGFloat itemWidth = floor(gridViewWidth / self.gridView.columnCount);
            self.gridView.rowHeight = itemWidth;
        }
    }
    
    for (NSInteger i = 0; i < self.gridView.subviews.count; i++) {
        UIView *item = self.gridView.subviews[i];
        item.qmui_borderPosition = QMUIBorderViewPositionLeft | QMUIBorderViewPositionTop;
        if ((i % self.gridView.columnCount == self.gridView.columnCount - 1) || (i == self.gridView.subviews.count - 1)) {
            // 每行最后一个，或者所有的最后一个（因为它可能不是所在行的最后一个）
            item.qmui_borderPosition |= QMUIBorderViewPositionRight;
        }
        if (i + self.gridView.columnCount >= self.gridView.subviews.count) {
            // 那些下方没有其他 item 的 item，底部都加个边框
            item.qmui_borderPosition |= QMUIBorderViewPositionBottom;
        }
    }
    
    CGFloat gridViewHeight = [self.gridView sizeThatFits:CGSizeMake(gridViewWidth, CGFLOAT_MAX)].height;
    self.gridView.frame = CGRectMake(self.scrollView.qmui_safeAreaInsets.left, 0, gridViewWidth, gridViewHeight);
    self.scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.gridView.frame), CGRectGetMaxY(self.gridView.frame));
}
@end
